import os
import shutil
import config_setting

from check_symbols import check_symbols
from file_copy import replace_directory_with_copy
from config_setting import nas_path_mapping
from util_ssh import execute_commands


def sync_newly_symbols(left_side_path, right_side_path, newly_sync_list, sync_suffix, symbol_folder):
    # base_left_path = rf"\\diskstation2\{left_side_name}"
    # base_right_path = rf"\\diskstation2\{right_side_name}"

    print(f"将新增的同步文件（夹）列表，复制至对端...待复制文件（夹）数量 {len(newly_sync_list)}")
    for folder_name in newly_sync_list:
        ln_command_list = []
        print(f"处理 {folder_name}...")
        print(f"\033[32m[Step1]\033[0m 如是目录，在右边创建空目录。如是文件，将文件复制至右边")
        if os.path.isdir(os.path.join(left_side_path, folder_name)):  # 如果是文件夹，则不用复制，仅建一个空文件夹，后面用goodsync同步
            os.mkdir(os.path.join(right_side_path, folder_name))
            print(f"已在右边创建空目录 {os.path.join(right_side_path, folder_name)}")
        else:  # 如果是文件，则要复制过去
            replace_directory_with_copy(os.path.join(left_side_path, folder_name),
                                        os.path.join(right_side_path, folder_name), real_delete=False)
            print(f"已复制文件 {os.path.join(left_side_path, folder_name)} -> {os.path.join(right_side_path, folder_name)}")
        # 执行bash命令必须用Linux路径，因此这里要用nas_path_mapping映射为Linux路径
        ln_command_list.append(
            f"ln -s {nas_path_mapping[left_side_path]}/{folder_name} {nas_path_mapping[left_side_path]}/{symbol_folder}/{folder_name}")
        ln_command_list.append(
            f"ln -s {nas_path_mapping[right_side_path]}/{folder_name} {nas_path_mapping[right_side_path]}/{symbol_folder}/{folder_name}")
        print(f"\033[32m[Step2]\033[0m 两边同时建立符号链接...")
        execute_commands(config_setting.hostname, config_setting.port, config_setting.username, config_setting.password, ln_command_list)


def sync_removal_symbols(left_side_path, right_side_path, removal_sync_list, sync_suffix, symbol_folder):
    # base_left_path = rf"\\diskstation2\{left_side_name}"
    # base_right_path = rf"\\diskstation2\{right_side_name}"
    unlink_command_list = []
    print(f"\033[32m[Step1]\033[0m 对两边符号进行删除操作...待删除符号数量 {len(removal_sync_list)}")
    for folder_name in removal_sync_list:
        # 这里左边因为是已经手工改过名，去除了__sync后缀，所以左边的符号链接已经是无效的了，但是右边的符号仍然是有效的。所以先要unlink，再对右边的文件改名。
        unlink_command_list.append(f"find {nas_path_mapping[left_side_path]}/{symbol_folder}/{folder_name} -type l -delete")
        unlink_command_list.append(f"find {nas_path_mapping[right_side_path]}/{symbol_folder}/{folder_name} -type l -delete")
    execute_commands(config_setting.hostname, config_setting.port, config_setting.username, config_setting.password, unlink_command_list)
    # 对右边的文件进行改名
    print(f"\033[32m[Step2]\033[0m 对右边的文件进行改名操作...待改名文件列表元素数量 {len(removal_sync_list)}")
    for folder_name in removal_sync_list:
        # shutil.move(os.path.join(base_right_path, folder_name), os.path.join(base_right_path, folder_name.replace("__sync", "")))
        if os.path.isdir(os.path.join(right_side_path, folder_name)):
            print(f"移动文件夹: {os.path.join(right_side_path, folder_name)} -> {os.path.join(right_side_path, folder_name.removesuffix(sync_suffix))}")
            shutil.move(os.path.join(right_side_path, folder_name),
                        os.path.join(right_side_path, folder_name.removesuffix(sync_suffix)))
        else:
            print(f"移动文件: {os.path.join(right_side_path, folder_name)} -> {os.path.join(right_side_path, os.path.splitext(folder_name)[0] + sync_suffix + os.path.splitext(folder_name)[1])}")
            shutil.move(os.path.join(right_side_path, folder_name), os.path.join(right_side_path, os.path.splitext(folder_name)[0] + sync_suffix + os.path.splitext(folder_name)[1]))

if __name__ == "__main__":
    left_side_path = rf"\\diskstation2\8192G_01"
    right_side_path = rf"\\diskstation2\8192G_02"

    result, todo_list = check_symbols(left_side_path)
    sync_newly_symbols(left_side_path, right_side_path, todo_list)
    sync_removal_symbols(left_side_path, right_side_path, todo_list)
